<template>
  <div class="layout_card">
    <el-card>
      <el-form :inline="true" class="filter_section">
        <el-form-item label="角色名称">
          <el-input placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="default">搜索</el-button>
          <el-button
            type="info"
            size="danger"
            @click="settingStore.refresh = !settingStore.refresh"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="" style="margin: 10px 0 0">
      <el-card>
        <div class="save_btns">
          <el-button type="primary" size="default" @click="OPEN_DIALOG()">
            添加角色
          </el-button>
          <el-button
            size="danger"
            :disabled="DELETE_IDS ? false : true"
            @click="SELECT_DELETE_ATTR"
          >
            批量删除
          </el-button>
        </div>

        <div class="table_section" style="margin: 10px 0">
          <el-table
            :data="tableData"
            stripe
            border
            @selection-change="TABLE_SELECT_CALLBACK"
          >
            <el-table-column type="selection" align="center" />
            <el-table-column prop="id" label="id" width="100" />
            <el-table-column prop="roleName" label="用户角色" />
            <el-table-column prop="createTime" label="创建时间" width="200" />
            <el-table-column prop="updateTime" label="更新时间" width="200" />
            <el-table-column
              label="操作"
              fixed="right"
              width="280"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  type="primary"
                  icon="User"
                  size="small"
                  title="分配角色"
                  @click="OPEN_ROLE_DIALOG(row.id)"
                >
                  分配权限
                </el-button>

                <el-button
                  type="primary"
                  icon="Edit"
                  size="small"
                  title="编辑"
                  @click="OPEN_DIALOG(row.id)"
                >
                  编辑
                </el-button>

                <el-button
                  type="danger"
                  icon="Delete"
                  size="small"
                  title="删除"
                  @click="DELETE_ATTR(row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="pagination_section">
          <el-pagination
            v-model:current-page="form.pageNo"
            v-model:page-size="form.limit"
            :page-sizes="[10, 20, 50, 100]"
            background
            layout="prev, pager, next,jumper, ->,sizes,total "
            :total="total"
            @size-change="GET_LIST"
            @current-change="GET_LIST"
          />
        </div>
      </el-card>
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
      <el-form :model="userData" ref="ruleFormRef" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="userData.roleName"
            placeholder="请输入角色名称"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CLOSE_DIALOG">取消</el-button>
          <el-button type="primary" @click="ADDUPDATE_DIALOG">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="roleDialogVisible" title="分配权限" width="500">
      <el-form :model="userData">
        <el-form-item label="角色名称">
          <el-input
            v-model="userData.roleName"
            placeholder="请输入角色名称"
            autocomplete="off"
            disabled
          />
        </el-form-item>

        <el-form-item label="权限列表">
          <el-tree
            ref="treeRef"
            style="max-width: 400px; max-height: 400px; overflow: auto"
            :data="roleList"
            show-checkbox
            default-expand-all
            :default-checked-keys="checkRoleIds"
            node-key="id"
            highlight-current
            :props="{
              children: 'children',
              label: 'name',
            }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CLOSE_ROLE_DIALOG">取消</el-button>
          <el-button type="primary" @click="EDIT_ROLE_DIALOG">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: 'roleLayout',
}
</script>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules, TreeInstance } from 'element-plus'
import { onMounted, onBeforeUnmount, ref, reactive } from 'vue'
import { publicConfirm } from '@/utils/handleData'

import { reqAddOrUpdateTrademark, reqDeletTrademark } from '@/api/product'

import { resRoleListById, resRoleList } from '@/api/acl'
import type {} from '@/api/acl/type'
import useAttributeCate from '@/store/modules/attributeCateStore'
import useSettingStore from '@/store/modules/settingStore'

const treeRef = ref<TreeInstance>()

let AttributeCateStore = useAttributeCate()

let settingStore = useSettingStore()
onMounted(() => {
  GET_LIST()
})
onBeforeUnmount(() => {})

let total = ref<number>(1)
let form = reactive({
  pageNo: 1,
  limit: 10,
})
let tableData = ref<any>([])
let roleList = ref<any>([])

let DELETE_IDS = ref<string>('')

const dialogVisible = ref(false)
let dialogTitle = ref('')

const roleDialogVisible = ref(false)

const ruleFormRef = ref<FormInstance>()
const userData_init = {
  id: '',
  roleName: '',
}
let userData = reactive({ ...userData_init })

const GET_LIST = async () => {
  Object.assign(form, { category2Id: AttributeCateStore.key_third })
  let result: any = await resRoleList(form)
  if (result.code == 200) {
    tableData.value = result.data.records
    total.value = result.data.total
  }
}

// 删除SPU
const DELETE_ATTR = async (id = 0) => {
  const flag = await publicConfirm({
    title: '提示',
    content: '确认删除该角色？',
  })
  let type = '删除'
  if (flag) {
    let result: any = await reqDeletTrademark(id)
    if (result.code == 200) {
      ElMessage({
        type: 'success',
        message: `${type}成功`,
      })
      GET_LIST()
    } else {
      ElMessage({
        type: 'error',
        message: `${type}失败`,
      })
    }
  } else {
    ElMessage({
      type: 'info',
      message: `取消${type}`,
    })
  }
}

const SELECT_DELETE_ATTR = async () => {
  const flag = await publicConfirm({
    title: '提示',
    content: '确认批量删除角色？',
  })
  let type = '删除'
  if (flag) {
    let result: any = await reqDeletTrademark(DELETE_IDS.value)
    if (result.code == 200) {
      ElMessage({
        type: 'success',
        message: `${type}成功`,
      })
      DELETE_IDS.value = ''
      window.location.reload()
    } else {
      ElMessage({
        type: 'error',
        message: `${type}失败`,
      })
    }
  } else {
    ElMessage({
      type: 'info',
      message: `取消${type}`,
    })
    DELETE_IDS.value = ''
    window.location.reload()
  }
}

const ADDUPDATE_DIALOG = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(userData)
  let type = '添加'
  if (userData.id) {
    type = '修改'
  }
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
    window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: `${type}成功`,
    })
  }
  CLOSE_DIALOG()
}
const OPEN_DIALOG = (id = 0) => {
  //   console.log(id)
  INIT_DIALOG()
  if (id > 0) {
    //修改
    dialogTitle.value = '编辑角色'
    const found = tableData.value.find((item) => item.id === id)
    if (found) {
      Object.assign(userData, found)
    }
  } else {
    // 添加
    dialogTitle.value = '添加角色'
  }
  dialogVisible.value = true
}

const INIT_DIALOG = () => {
  Object.assign(userData, userData_init)
  if (!ruleFormRef.value) return
  ruleFormRef.value.clearValidate('roleName')
}
const CLOSE_DIALOG = () => {
  dialogVisible.value = false
}

const rules = reactive<FormRules<any>>({
  roleName: [{ required: true, message: '请输入角色姓名', trigger: 'blur' }],
})

const OPEN_ROLE_DIALOG = async (id = 0) => {
  await INIT_ROLE_DIALOG()
  const found = tableData.value.find((item) => item.id === id)
  if (found) {
    Object.assign(userData, found)
    // if (userData.roleName) {
    //   checkedRoles.value = userData.roleName
    //     .split(',')
    //     .reduce((p: any[], n) => {
    //       let role = roleList.value.find((item) => item.roleName == n)
    //       //   console.log(role)
    //       p.push(role.id)
    //       return p
    //     }, [])
    // }
  }
  roleDialogVisible.value = true
}
const INIT_ROLE_DIALOG = async () => {
  Object.assign(userData, userData_init)
  await GET_ROLE_LIST()
}
const GET_ROLE_LIST = async () => {
  Object.assign(form, { category2Id: AttributeCateStore.key_third })
  let result: any = await resRoleListById(form)
  if (result.code == 200) {
    roleList.value = result.data
    checkRoleIds.value = GET_ROLE_IDS(roleList.value)
  }
}

const GET_ROLE_IDS = (DATA: any, INIT: any = []) => {
  for (let index = 0; index < DATA.length; index++) {
    let item = DATA[index]
    if (item.children.length > 0) {
      if (item.level == 4) {
        if (item.select) {
          INIT.push(item.id)
        }
      } else {
        GET_ROLE_IDS(item.children, INIT)
      }
    } else {
      if (item.select) {
        INIT.push(item.id)
      }
    }
  }
  return INIT
}

const CLOSE_ROLE_DIALOG = () => {
  roleDialogVisible.value = false
}

// let checkedRoles = ref<any>([])

const EDIT_ROLE_DIALOG = async () => {
  let keys = treeRef.value!.getCheckedKeys(false)
  let result: any = await reqAddOrUpdateTrademark(keys)
  let type = '分配角色'
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
  } else {
    ElMessage({
      type: 'error',
      message: `${type}失败`,
    })
  }
  CLOSE_ROLE_DIALOG()
}

const TABLE_SELECT_CALLBACK = (selects) => {
  DELETE_IDS.value = selects.map((item) => item.id).join(',')
}

let checkRoleIds = ref([])
</script>

<style scoped lang="scss">
.filter_section .el-input {
  --el-input-width: 220px;
}
.filter_section .el-input {
  --el-select-width: 220px;
}
</style>
